package com.ly.sy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ly.sy.entity.Course;
import com.ly.sy.entity.Homework;
import com.ly.sy.entity.Syuser;
import com.ly.sy.entity.Video;
import com.ly.sy.service.CourseService;
import com.ly.sy.service.HomeworkService;
import com.ly.sy.service.SyuserService;
import com.ly.sy.service.VideoService;
import com.ly.sy.util.SendSms;
import com.ly.sy.util.randomCode;
import com.ly.sy.util.saveObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liangyu
 * @since 2020-11-11
 */
@Controller
@RequestMapping(value = "/sy/syuser",method = RequestMethod.POST)
public class SyuserController {
//    http://localhost:8080/sy/syuser/findAlluser
//    注入依赖
    @Autowired
    private SyuserService syuserService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private VideoService videoService;
    @Autowired
    private HomeworkService homeworkService;
//    查询所有用户
    @GetMapping("findAlluser")
    @ResponseBody
    public List<Syuser> findAlluser(){
        List<Syuser> syuserList = syuserService.list(null);
        return syuserList;
    }
//    用户登录
    @PostMapping("userlogin")
    public String userlogin(String username,String password, HttpSession session){

        if(username == "" || password == ""){
            session.setAttribute("message","1");
            return "User/userlogin";
        }
        Syuser users = syuserService.findByuserNameAnduserPwd(username,password);

        if(ObjectUtils.isEmpty(users)){
            session.setAttribute("message","2");
            return "User/userlogin";
        }else{

            session.setAttribute("User",users);
            return "redirect:/sy/course/goindex";
        }

    }
//    跳转到用户登录页面
    @GetMapping("/gologin")
    public String gologin(){

        return "User/userlogin";
    }
//  找回密码
    @GetMapping("findpassword")
    public String findpassword(){
        return "User/findpassword";
    }
    @PostMapping("inspecapply")
    @ResponseBody
    public String inspecapply(@RequestParam String userName,
                              @RequestParam String userPwd,
                              @RequestParam String userPhone,
                              @RequestParam String code,
                              HttpSession session){
        if(!code.equals(session.getAttribute("redCode"))){
            return "验证码错误";
        }
        Syuser syuser = syuserService.findpassword(userName,userPhone);
        if(!ObjectUtils.isEmpty(syuser)){
            syuser.setUserPwd(userPwd);
        }
        syuserService.updateById(syuser);
        session.removeAttribute("redCode");
        return "ok";
    }
//用户退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("User");
        session.removeAttribute("message");
        session.removeAttribute("coursexk");
        session.removeAttribute("courseidList");
        return "User/userlogin";
    }
//跳转到注册页面
    @GetMapping("goregistered")
    public String goregistered(){
        return "User/registered";
    }
//    跳转到申请教师身份页面
    @GetMapping("permissions")
    public String permissions(){
        return "User/permissions";
    }
//向手机发送验证码
    @PostMapping("ShortMessage")
    @ResponseBody
    public String goShortMessage(@RequestParam String phoneNum,HttpSession session){
        if(phoneNum.length()!=11){
            return "请输入正确的手机号码";
        }
        String redCode = randomCode.reCode();
        System.out.println("生成的验证码："+redCode);
        System.out.println("接收验证码的手机："+phoneNum);
        //将验证码存到session
        session.setAttribute("redCode",redCode);
        System.out.println("session中的验证码："+session.getAttribute("redCode"));

        SendSms.sendShortMessage(redCode,phoneNum);

        return "true";
    }
//    ajax异步校验用户名
    @PostMapping("eqname")
    @ResponseBody
    public String eqname(@RequestParam String userName){
        System.out.println("获取到的name："+userName);
        Syuser uname = syuserService.findByName(userName);
        if(!ObjectUtils.isEmpty(uname)){
            System.out.println("被占用的用户名："+userName);
            return "true";
        }else return "false";
    }
//    与ajax实现多重检验用户名是否重复，如无重复则提交操作用户注册成功
    @PostMapping("adduser")
    @ResponseBody
    public String adduser(@RequestParam String userName,
                          @RequestParam String userPwd,
                          @RequestParam String userPhone,
                          @RequestParam String code,
                          HttpSession session){
        if(!code.equals(session.getAttribute("redCode"))){
            return "验证码错误";
        }
        Syuser syuser = new Syuser();
        syuser.setUserName(userName);
        syuser.setUserPwd(userPwd);
        syuser.setUserPhone(userPhone);
        String Imgsrc = "/imges/user.jpg";
        syuser.setUserImg(Imgsrc);
        System.out.println(syuser);
//        用户名验证
        Syuser uname = syuserService.findByName(userName);
        if(!ObjectUtils.isEmpty(uname)){
            System.out.println("被占用的用户名："+userName);
            return "该用户名已被占用";
        }else {
//            添加用户
            boolean saveuser =  syuserService.save(syuser);
            System.out.println("用户注册状态："+saveuser);
            session.removeAttribute("redCode");
            return "ok";
        }

    }
/**
 * @savepermissions保存教师身份申请操作
 * 改变权限
 * @return String
 *
 * **/
    @PostMapping("savepermissions")
    @ResponseBody
    public String savepermissions( @RequestParam String userPhone,
                                   @RequestParam String code,
                                   HttpSession session){
        if(!code.equals(session.getAttribute("redCode"))){
            return "验证码错误";
        }
        Syuser syuser = (Syuser) session.getAttribute("User");
        syuser.setUserPrivilege(1);
        syuserService.updateById(syuser);
        session.setAttribute("User",syuser);
        session.removeAttribute("redCode");
        return "ok";
    }

//跳转到关于我们
    @GetMapping("aboutwe")
    public String aboutwe(){
        return "User/aboutwe";
    }
//跳转到sy课堂主页面
    @GetMapping("syclass")
    public String syclass(HttpSession session){
        Syuser syuser = (Syuser) session.getAttribute("User");
        if(!ObjectUtils.isEmpty(syuser)){
            //获取本用户的发布课程
            session.removeAttribute("myclass");
            session.removeAttribute("myvideoofclass");
            session.removeAttribute("myhomeworkbyclass");
            QueryWrapper<Course> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("course_auid",syuser.getUserId());
            List<Course> courseList = courseService.list(queryWrapper);
            if(!ObjectUtils.isEmpty(courseList)){
                //获取第一堂课的课件
                QueryWrapper<Video> queryWrapper1=new QueryWrapper<>();
                queryWrapper1.eq("course_id",courseList.get(0).getCourseId());
                List<Video> avideo = videoService.list(queryWrapper1);
                //获去第一堂课的练习
                QueryWrapper<Homework> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("course_id",courseList.get(0).getCourseId());
                List<Homework> ahomework = homeworkService.list(queryWrapper2);
                session.setAttribute("acoursename",courseList.get(0).getCourseName());
                session.setAttribute("onecourseId",courseList.get(0).getCourseId());
                session.setAttribute("myclass",courseList);
                session.setAttribute("myvideoofclass",avideo);
                session.setAttribute("myhomeworkbyclass",ahomework);
            }
        }

        return "User/syclass";
    }
//    每一门我发布的课程的相关信息
    @GetMapping("getoneclass")
    public String getoneclass(@RequestParam Integer courseId, HttpSession session){
        session.removeAttribute("myvideoofclass");
        session.removeAttribute("myhomeworkbyclass");
        Course course = courseService.getById(courseId);
        QueryWrapper<Video> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("course_id",courseId);
        List<Video> avideo = videoService.list(queryWrapper1);
        //获去第一堂课的练习
        QueryWrapper<Homework> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("course_id",courseId);
        List<Homework> ahomework = homeworkService.list(queryWrapper2);
        session.setAttribute("acoursename",course.getCourseName());
        session.setAttribute("myvideoofclass",avideo);
        session.setAttribute("myhomeworkbyclass",ahomework);
        session.setAttribute("onecourseId",courseId);
        return "User/syclass";
    }
//跳转到个人中心
    @GetMapping("gopc")
    public String gopc(){
        return "User/userPC";
    }
//安全中心
    @GetMapping("SeCenter")
    public String SeCenter(HttpSession session){
        session.setAttribute("check",0);
        return "User/SeCenter";
    }
//上传图片
    @PostMapping("uploadFile")
    @ResponseBody
    public String uploadFile(
            @RequestParam("imageData") MultipartFile file,
            HttpSession session
    ){
        if(ObjectUtils.isEmpty(file)){
            System.out.println("没有获取到文件");
            return "null";
        }
        System.out.println("获取到的上传文件："+file);
//      上传图片到oss，并返回一个图片路径url
        String url = saveObject.updown(file);

        System.out.println("图片上传操作完成");
        System.out.println("图片路径："+url);
//      取出当前session中的User对象
        Syuser user = (Syuser) session.getAttribute("User");
        user.setUserImg(url);
        System.out.println("用户id："+user.getUserId());

//        先改好数据放到一个对象中，再将整个user对象给updateById实现数据修改
        syuserService.updateById(user);
        return "true";
    }
//重新获取用户信息刷新页面
    @GetMapping("reuserdata")
    public String reuserdata(HttpSession session){

        Syuser user = syuserService.selectById((Syuser) session.getAttribute("User"));
        System.out.println("根据id查询返回的用户："+user);
        session.setAttribute("User",user);
        return "User/userPC";
    }

//跳转到修改手机号码页面
    @GetMapping("gouqphone")
    public String gouqphone(){
        return "User/UserchPhone";
    }
//跳转到修改密码页面
    @GetMapping("gouqpassword")
    public String gouqpassword(){
        return "User/Userchpad";
    }

//修改密码
    @PostMapping("uppwd")
    @ResponseBody
    public String uppwd(@RequestParam String userPwd,
                        @RequestParam String code,
                        HttpSession session){
        if(!code.equals(session.getAttribute("redCode"))){
            return "验证码错误";
        }
        Syuser user = (Syuser) session.getAttribute("User");
        user.setUserPwd(userPwd);
        syuserService.updateById(user);
        return "ok";
    }
    //重新获取用户信息刷新页面
    @GetMapping("ruserdata")
    @ResponseBody
    public String ruserdata(HttpSession session){

        Syuser user = syuserService.selectById((Syuser) session.getAttribute("User"));
        System.out.println("根据id查询返回的用户："+user);
        session.setAttribute("check",1);
        session.setAttribute("User",user);
        return "密码修改成功，请记住新密码："+user.getUserPwd();
    }
    //修改手机号
    @PostMapping("upphone")
    @ResponseBody
    public String upphone(@RequestParam String userPhone,
                        @RequestParam String code,
                        HttpSession session){
        if(!code.equals(session.getAttribute("redCode"))){
            return "验证码错误";
        }
        Syuser user = (Syuser) session.getAttribute("User");
        user.setUserPhone(userPhone);
        syuserService.updateById(user);
        return "ok";
    }
    //重新获取用户信息刷新页面
    @GetMapping("ruserdataByphone")
    @ResponseBody
    public String ruserdataByphone(HttpSession session){

        Syuser user = syuserService.selectById((Syuser) session.getAttribute("User"));
        System.out.println("根据id查询返回的用户："+user);
        session.setAttribute("check",1);
        session.setAttribute("User",user);
        return "手机号码修改成功";
    }


//*********************************************admin*************************************************
    @GetMapping("useradmin")
    public String useradmin(HttpSession session){
        List<Syuser> syuserList = syuserService.list(null);
        session.setAttribute("syuserofadmin",syuserList);
        return "/admin/useradmin";
    }
    //权限修改
    @PostMapping("changePri")
    @ResponseBody
    public String changePri(@RequestParam Integer userId){
        Syuser syuser = syuserService.getById(userId);
        if(syuser.getUserPrivilege()==0){
            syuser.setUserPrivilege(1);
            syuserService.updateById(syuser);
            return "教师";
        }else {
            syuser.setUserPrivilege(0);
            syuserService.updateById(syuser);
            return "学生";
        }

    }
    //注销用户
    @PostMapping("deleteuser")
    @ResponseBody
    public boolean deleteuser(@RequestParam Integer userId){
        return syuserService.removeById(userId);
    }
    //模糊搜索
    @GetMapping("search")
    @ResponseBody
    public List<Syuser> search(@RequestParam String searchstr){
        List<Syuser> syuserList = syuserService.userlikelist(searchstr);
        return syuserList;
    }

}

